package team.shixi.houtai.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import team.shixi.houtai.common.Result;
import team.shixi.houtai.common.ResultUtil;
import team.shixi.houtai.entity.Goods;
import team.shixi.houtai.entity.Order;
import team.shixi.houtai.entity.User;
import team.shixi.houtai.mapper.GoodsMapper;
import team.shixi.houtai.mapper.UserMapper;
import team.shixi.houtai.service.GoodsService;
import team.shixi.houtai.service.OrderService;
import team.shixi.houtai.service.UserService;

import java.util.List;


/**
 * @author Zhangrt
 * @Description
 * @create 2023-01-12 13:50
 */
@RestController
@RequestMapping("/wx")
public class WxController {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    @PostMapping("/adduser")
    public Result<?> adduser(@RequestBody User user){

        String username = user.getUsername();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);
        User one = userService.getOne(queryWrapper);
        if (one!=null){
            return Result.error("用户已存在");
        }
        user.setStatus(1);
        userService.save(user);
        return Result.success();
    }

    @GetMapping("/getusers")
    public List<User> getusers(){
        List<User> userList = userMapper.selectList(null);
        return userList;
    }

    @PostMapping("/addorder")//新增订单
    public Result<?> addorder(@RequestBody Order order){

        int goodsid = order.getGid();
        int count = order.getCount();//购买数量
        Goods goods = goodsService.getById(goodsid);
        int amount = goods.getAmount();//库存数量
        amount = amount - count;
        goods.setAmount(amount);
        goodsService.updateById(goods);

        orderService.save(order);
        return Result.success();
    }


    @GetMapping("/goodsquery")//查询数据
    public Result<?> findgoods(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search){

        Page<Goods> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        Page<Goods> goodsPage = goodsMapper.selectWxAll(page, queryWrapper);

        return ResultUtil.success(goodsPage);

    }
}
